package org.wx.thread.thread;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description: 多窗口卖票的线程
 * @author: wangxun
 * @createDate: 2021/11/26
 * @version: 1.0
 */
@Slf4j
public class TicketThead implements Runnable {
    private int count = 500;
    // 比较器
    public static AtomicInteger comparer = new AtomicInteger();
    private void takeTicket(){
        // 同步锁 synchronized 就保证了可见性，所以不用加volatile
        synchronized (this){
            comparer.incrementAndGet();
            if(count>0){
                log.info("【{}】窗口售第【{}】张票",Thread.currentThread().getName(),count--);
            }else{
                log.info("【{}】窗口售空",Thread.currentThread().getName());
            }
        }
    }

    @Override
    public void run() {
        while (count>0){
            takeTicket();
        }

    }

    @SneakyThrows
    public static void main(String[] args) {
        TicketThead ticketThead = new TicketThead();
        Thread t1 = new Thread(ticketThead);
        Thread t2 = new Thread(ticketThead);
        Thread t3 = new Thread(ticketThead);

        t1.start();
        t2.start();
        t3.start();

        t1.join();
        t2.join();
        t3.join();

        log.info("比较器：{}",TicketThead.comparer.get());

    }
}
